//app.js
var api = require('/utils/api.js');
var oauthUrl = api.getOauthUrl();
App({
  data:{
    userInfo: {},
    backUserInfo: {},//后台得到的微信用户信息
    hasUserInfo: false,
    openId: "",
    nickName: "",
    canIUse: wx.canIUse('button.open-type.getUserInfo')
  },
  onLaunch: function () {
    //调用API从本地缓存中获取数据
    var logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs);
    //1.静默操作获取用户信息 调用wx.login
    var that = this;
    wx.login({
      success: function (res) {
        var code = res.code;//2.登录凭证code
        if (null != code) {
          wx.getUserInfo({
            success: function (ress) {
              console.log('res===' + ress);
              //3.请求自己的服务器，解密用户信息 
              wx.request({
                url: oauthUrl,
                method: 'post',
                header: {
                  'content-type': 'application/x-www-form-urlencoded'
                },
                data: { encryptedData: ress.encryptedData, iv: ress.iv, code: code },
                success: function (res) {
                  that.globalData.userInfo = res.data
                }, fail: function (res) {
                  var res = "";
                  that.globalData.backUserInfo = res;
                }
              })
            }
          })
        }
      }
    })
    if (that.globalData.userInfo) {
        userInfo=app.globalData.userInfo,
        hasUserInfo=true
    } else if (this.data.canIUse) {
      // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      that.userInfoReadyCallback = res => {
          that.globalData.userInfo = res.userInfo,
          hasUserInfo = true
      }
    } else {
      // 在没有 open-type=getUserInfo 版本的兼容处理
      wx.getUserInfo({
        success: res => {
            that.globalData.userInfo = res.userInfo,
            hasUserInfo=true
        }
      })
    }
  },
  getUserInfo:function(cb){
    var that = this
    if(this.globalData.userInfo){
      typeof cb == "function" && cb(this.globalData.userInfo)
    }else{
      //调用登录接口
      wx.login({
        success: function () {
          wx.getUserInfo({
            success: function (res) {
              console.info("app.js===" + res.userInfo)
              that.globalData.userInfo = res.userInfo
              typeof cb == "function" && cb(that.globalData.userInfo)
            }
          })
        }
      })
    }
  },
  globalData:{
    userInfo:null,
    backUserInfo:null
  }
})